<template>
  <el-dialog
    v-model="dialogVisible"
    :title="
      level
        ? `${optionInfo?.type === 'add' ? '添加' : '编辑'}${level === 1 ? (optionInfo?.type === 'add' ? '' : '一级') : level === 2 ? '二级' : '三级'}规格`
        : '添加规格'
    "
    width="1000"
    align-center
    @close="closeDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="form" label-width="auto" :rules="rules" style="max-width: 600px">
      <el-form-item label="关联分类" prop="classify">
        <el-tree-select
          v-model="form.classify"
          :data="optionInfo.currentClassNode"
          check-strictly
          :render-after-expand="false"
          style="width: 240px"
          node-key="categoryId"
          :props="{
            label: 'name',
            children: 'children'
          }"
        />
      </el-form-item>
      <el-form-item label="分类预览" style="margin-top: 20px">
        <p>{{ optionInfo.classifyTitle }}</p>
      </el-form-item>
    </el-form>

    <div class="hr"></div>
    <div class="form-list">
      <el-form
        v-for="(item, index) in formList"
        :key="index"
        :inline="true"
        :model="item"
        ref="formRef"
        class="demo-form-inline"
        v-show="item.delFlag === 0"
      >
        <!-- 一级 -->
        <div class="level1">
          <el-row>
            <el-col :span="20">
              <el-form-item label="一级规格名称" prop="name" :rules="{ required: true, message: '', trigger: ['blur'] }">
                <el-input
                  v-model.trim="item['name']"
                  placeholder="请输入"
                  clearable
                  maxlength="20"
                  :disabled="
                    (optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1) || item.quote === 1
                  "
                  style="width: 250px"
                />
              </el-form-item>
              <el-form-item label="" prop="levelType" :rules="{ required: true, message: '', trigger: ['blur', 'change'] }">
                <el-select
                  v-model="item.levelType"
                  placeholder="请选择"
                  style="width: 140px"
                  :disabled="
                    (optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1) || item.quote === 1
                  "
                >
                  <el-option :label="'单选框'" :value="1" />
                  <el-option :label="'输入框'" :value="2" />
                  <el-option :label="'规范数值输入'" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="顺序号">
                <el-input
                  v-model="item['sortOrder']"
                  type="number"
                  placeholder="请输入"
                  clearable
                  style="width: 80px"
                  min="1"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                />
                <!-- <el-button
                  v-if="optionInfo.type === 'edit'"
                  type="primary"
                  link
                  class="add-attr"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                  @click="clickAddAttrTips(item)"
                  >添加属性说明</el-button
                > -->
              </el-form-item>
            </el-col>
            <el-col :span="4" class="del-wrap">
              <el-icon
                class="del-icon f16"
                @click="delLevel1(item, index)"
                :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                ><Delete
              /></el-icon>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20" class="mt18" style="padding-left: 100px">
              <!-- <el-form-item label="是否筛选" style="margin-right: 60px">
                <el-radio-group
                  v-model="item['screen']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">是</el-radio>
                  <el-radio :label="0" :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item label="是否必填" style="margin-right: 60px">
                <el-radio-group
                  v-model="item['required']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">是</el-radio>
                  <el-radio :label="0" :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group
                  v-model="item['status']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">显示</el-radio>
                  <el-radio :label="0" :value="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="hr" style="margin: 20px -16px"></div>
          <el-row>
            <el-col :span="20" v-if="item.levelType === 1">
              <el-form-item label="属性展现方式" style="margin-right: 60px">
                <el-radio-group v-model="item['speType']" :disabled="level === 2" @change="changeShowType(item, $event)">
                  <el-radio :label="1" :value="1">文字</el-radio>
                  <el-radio :label="2" :value="2">颜色</el-radio>
                  <el-radio :label="3" :value="3">图片</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="item.levelType === 3" class="standard-input">
              <div>
                <el-input
                  id="test"
                  v-model="item.propTemplate"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                  style="width: 100%"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入"
                  @click="
                    e => {
                      handleBlur(e, index);
                    }
                  "
                  @blur="
                    e => {
                      handleBlur(e, index);
                    }
                  "
                  @keyup.delete="
                    e => {
                      handleKeyUp(e, index);
                    }
                  "
                />

                <!-- <jsxCom :str="item.textarea" /> -->
              </div>
              <div
                class="mt14 mb14"
                style="display: flex; justify-content: space-between"
                v-if="!((optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1))"
              >
                <div>
                  <el-button type="primary" link @click="getEmo(index, '【数值】')" class="f12">
                    <img class="mr10" src="@/assets/images/insert-icon.png" alt="" style="width: 16px; height: 16px" />插入数值
                  </el-button>
                  <el-button type="primary" link @click="getEmo(index, '【字符】')" class="f12">
                    <img class="mr10" src="@/assets/images/insert-icon.png" alt="" style="width: 16px; height: 16px" />插入字符
                  </el-button>
                </div>
                <el-button type="primary" link class="f12" @click="clickView(item)" :disabled="!item.propTemplate">
                  <img class="mr10" src="@/assets/images/eyes-icon.png" alt="" style="width: 16px; height: 16px" />预览
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 二级 -->
        <div class="level2" v-if="item.levelType === 1">
          <el-row v-if="item?.speType">
            <!-- 文字 -->
            <el-col :span="20" v-if="item?.speType === 1">
              <template v-for="(item2, index2) in item.children" :key="index2">
                <div class="level2-item" v-if="item2.delFlag === 0">
                  <el-form-item
                    label="二级属性名称"
                    :prop="`children.${index2}.name`"
                    :rules="{ required: true, message: '', trigger: ['blur'] }"
                  >
                    <el-input
                      clearable
                      v-model.trim="item2['name']"
                      placeholder="请输入"
                      maxlength="40"
                      :disabled="level === 3 || item2.quote === 1"
                      style="width: 250px"
                    />
                  </el-form-item>
                  <el-form-item label="顺序号">
                    <el-input
                      v-model="item2['sortOrder']"
                      type="number"
                      placeholder="请输入"
                      clearable
                      style="width: 80px"
                      min="1"
                      :disabled="level === 3"
                    />
                    <p class="ml20 f16">
                      <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                    </p>
                  </el-form-item>
                </div>
              </template>
              <el-button @click="addLevel2(item)" type="primary" link :icon="CirclePlusFilled" class="add-item add-item2">
                继续添加
              </el-button>
            </el-col>

            <!-- 颜色 -->
            <el-col :span="20" v-else-if="item?.speType === 2">
              <template v-for="(item2, index2) in item.children" :key="index2">
                <div class="level2-item" v-if="item2.delFlag === 0">
                  <el-form-item
                    label="二级属性名称"
                    :prop="`children.${index2}.name`"
                    :rules="{ required: true, message: '', trigger: ['blur'] }"
                  >
                    <el-input
                      clearable
                      v-model.trim="item2['name']"
                      placeholder="请输入"
                      maxlength="40"
                      :disabled="level === 3 || item2.quote === 1"
                      style="width: 250px"
                    />
                  </el-form-item>
                  <el-form-item label="">
                    <el-color-picker v-model="item2['statsText']" show-alpha :predefine="predefineColors" />
                  </el-form-item>
                  <el-form-item label="顺序号">
                    <el-input
                      v-model="item2['sortOrder']"
                      type="number"
                      placeholder="请输入"
                      clearable
                      style="width: 80px"
                      min="1"
                      :disabled="level === 3"
                    />
                  </el-form-item>
                  <p class="ml10 mr12 f16" style="display: inline-block">
                    <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                  </p>
                </div>
              </template>
              <el-button @click="addLevel2(item)" type="primary" link :icon="CirclePlusFilled" class="add-item add-item2">
                继续添加
              </el-button>
            </el-col>

            <!-- 图片 -->
            <el-col :span="20" v-if="item?.speType === 3">
              <template v-for="(item2, index2) in item.children" :key="index2">
                <div class="level2-item" v-if="item2.delFlag === 0">
                  <el-form-item
                    label="二级属性名称"
                    :prop="`children.${index2}.name`"
                    :rules="{ required: true, message: '', trigger: ['blur'] }"
                  >
                    <el-input
                      clearable
                      v-model.trim="item2['name']"
                      placeholder="请输入"
                      maxlength="40"
                      :disabled="level === 3 || item2.quote === 1"
                      style="width: 250px"
                    />
                  </el-form-item>
                  <el-form-item label="顺序号">
                    <el-input
                      v-model="item2['sortOrder']"
                      type="number"
                      placeholder="请输入"
                      clearable
                      style="width: 80px"
                      min="1"
                      :disabled="level === 3"
                    />
                    <p class="ml20 f16">
                      <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                    </p>
                  </el-form-item>

                  <div class="built_in_box">
                    <el-upload
                      disabled
                      class="avatar-uploader"
                      list-type="picture-card"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="
                        (file, fileList) => {
                          handleAvatarChangeIcon(item2, file, fileList);
                        }
                      "
                    >
                      <img
                        v-if="
                          item2['statsText'] && item2['statsText'].includes('http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/')
                        "
                        :src="item2['statsText']"
                        class="avatar"
                      />
                      <p v-else class="f12">
                        <el-icon><Plus /></el-icon>
                      </p>
                    </el-upload>
                  </div>
                </div>
              </template>
              <el-button @click="addLevel2(item)" type="primary" link :icon="CirclePlusFilled" class="add-item add-item2">
                继续添加
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-button
        v-if="JSON.stringify(optionInfo.formData) === '{}'"
        @click="addLevel1"
        type="primary"
        link
        :icon="CirclePlusFilled"
        class="add-item add-item1"
      >
        添加一级属性
      </el-button>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 插入数值、字符预览 -->
  <el-dialog v-model="dialogVisibleNS" align-center title="预览" width="810" :before-close="handleCloseNS">
    <jsxCom :str="viewCurrObj.propTemplate" />
  </el-dialog>

  <!-- 富文本编辑器 -->
  <el-dialog
    v-model="dialogEditorVisible"
    title="属性标签说明"
    width="800"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div style="border: 1px solid #ccc">
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="'default'" />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="'default'"
        @onCreated="handleCreated"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeEditorDialog">取消</el-button>
        <el-button type="primary" @click="submitEditor">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, shallowRef, onBeforeUnmount } from "vue";
import { Delete, CirclePlusFilled, Plus, View } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { getRichText, saveSassRichText } from "@/api/products/attribute";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { orgChildIdFindParent, getFolder, replaceNS } from "@/utils/index";
import jsxCom from "./jsxCom.vue";

const emit = defineEmits(["close", "submit"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        type: "add", //add edit
        formData: {},
        list: [],
        currentClassNode: [], //当前分类tree
        classifyTitle: "" //分类预览
      };
    }
  }
});

watch(
  () => props.optionInfo,
  val => {
    dialogVisible.value = val.isShow;
    level.value = val?.formData?.format ? val?.formData?.format.split("-").length : 0;
    val.currentClassNode.children = []; //回显商品分类下拉数据
    form.value.classify = val.currentClassNode[0].categoryId; //回显商品分类下拉数据
    console.log("传到子组件的数据", val.formData);
    const DATA = JSON.parse(JSON.stringify(val.formData));
    if (val.type === "add") {
      level.value = level.value + 1;
      formList.value = [{ children: [], required: 1, status: 1, speType: 1, sortOrder: 1, delFlag: 0 }]; //添加时，清空表单数据
      addReview(DATA); //新增时，回显数据
    } else {
      editReview(DATA); //编辑时，回显数据
    }
  },
  {
    deep: true
  }
);

const form = ref({});
const formRef = ref();
const rules = ref({
  classify: [{ required: true, message: "Please input Activity name", trigger: ["change", "blur"] }]
});
const level = ref(0);
const dialogEditorVisible = ref(false); //富文本编辑框
const dialogVisible = ref(false);
const formList = ref([
  {
    children: [],
    speType: 1,
    sortOrder: 1,
    delFlag: 0
  }
]);
const predefineColors = ref([
  "#ff4500",
  "#ff8c00",
  "#ffd700",
  "#90ee90",
  "#00ced1",
  "#1e90ff",
  "#c71585",
  "rgba(255, 69, 0, 0.68)",
  "rgb(255, 120, 0)",
  "hsv(51, 100, 98)",
  "hsva(120, 40, 94, 0.5)",
  "hsl(181, 100%, 37%)",
  "hsla(209, 100%, 56%, 0.73)",
  "#c7158577"
]);
const dialogVisibleNS = ref(false); //插入数值、字符 预览弹窗
const viewCurrObj = ref({});

// ===============================插入数值、字符==========================================================

const clickView = item => {
  dialogVisibleNS.value = true;
  setTimeout(() => {
    viewCurrObj.value = item;
  }, 50);
};

const handleCloseNS = () => {
  dialogVisibleNS.value = false;
};
const handleKeyUp = (e, index) => {
  if (isDel4.value) {
    formList.value[index].propTemplate = `${delStrStart.value}${delStrEnd.value}`;
  }
};
const cursorPos = ref(0); // 光标位置
const delStrStart = ref(""); // 删除字符开始的位置
const delStrEnd = ref(""); // 删除字符结束的位置
const isDel4 = ref(false);
const handleBlur = (e, index) => {
  cursorPos.value = e.srcElement.selectionStart;
  console.log("光标位置===", cursorPos.value);

  if (cursorPos.value >= 4) {
    delStrStart.value = formList.value[index].propTemplate.substring(0, cursorPos.value - 4);
    delStrEnd.value = formList.value[index].propTemplate.substring(cursorPos.value);
    if (formList.value[index].propTemplate[cursorPos.value - 1] === "】") {
      isDel4.value = true;
    } else {
      isDel4.value = false;
    }
    console.log("del===========", isDel4.value, delStrStart.value, "-", delStrEnd.value);
  } else {
    isDel4.value = false;
    delStrStart.value = "";
    delStrEnd.value = "";
  }
};

const getEmo = (index, str) => {
  if (!formList.value[index].propTemplate) {
    formList.value[index].propTemplate = str;
  } else {
    const start = formList.value[index].propTemplate.substring(0, cursorPos.value);
    const end = formList.value[index].propTemplate.substring(cursorPos.value);
    // console.log("aaaaaaaaaaa", start, end);
    formList.value[index].propTemplate = `${start}${str}${end}`;
  }
};

// =========================================================================================

/**
 *
 * @param {*} item  一级规格的完整数据
 * @param {*} speType 当前变化之后的展现方式
 */
const changeShowType = (item, speType) => {
  const ITEM = JSON.parse(JSON.stringify(props.optionInfo.formData)); //深度复制点击的table行的原始tree数据
  if (props.optionInfo.type === "add") {
    // 添加
    item.children = [{ delFlag: 0, sortOrder: 1 }];
  } else {
    //编辑

    if (level.value === 1) {
      //一级规格
      if (ITEM.speType !== speType) {
        // console.log(111);
        const _item = ITEM?.children.map(obj => {
          return {
            ...obj,
            statsText: "#ffffff"
          };
        });
        item.children = _item;
      } else {
        // console.log(222);
        item.children = ITEM?.children;
      }
    } else if (level.value === 2) {
      const parentsArr = orgChildIdFindParent(
        props.optionInfo.formData.specificationId,
        props.optionInfo.list,
        "specificationId"
      );
      // console.log("找到父级了===", parentsArr);
      //二级规格
      if (parentsArr[0].speType !== speType) {
        // console.log(333);
        item.children[0].statsText = "#ffffff";
      } else {
        // console.log(444);
        item.children = [ITEM];
      }
    }
  }
};

const addReview = formData => {
  if (JSON.stringify(formData) === "{}") return;
  const parentsArr = orgChildIdFindParent(formData.specificationId, props.optionInfo.list, "specificationId");
  let _formData = JSON.parse(JSON.stringify(formData));
  _formData.children = [];
  //%f转成【数值】 %s转成【字符】
  if (_formData.propTemplate) {
    _formData.propTemplate = replaceNS(_formData.propTemplate, -1);
  }
  if (level.value === 2) {
    _formData.children = [{ delFlag: 0 }];
    formList.value = [_formData];
    // console.log("添加，渲染二级===", formList.value, formData);
  } else if (level.value === 3) {
    formList.value = [
      {
        ...parentsArr[0],
        children: [_formData]
      }
    ];
    // console.log("添加，渲染三级===", formList.value, formData);
  }
};

const editReview = formData => {
  if (JSON.stringify(formData) === "{}") return;
  const parentsArr = orgChildIdFindParent(formData.specificationId, props.optionInfo.list, "specificationId");
  let _formData = JSON.parse(JSON.stringify(formData));
  //%f转成【数值】 %s转成【字符】
  if (_formData.propTemplate) {
    _formData.propTemplate = replaceNS(_formData.propTemplate, -1);
  }

  // _formData.children = [];
  if (level.value === 1) {
    formList.value = [_formData];
    // console.log("添加，渲染一级===", formList.value, formData);
  } else if (level.value === 2) {
    console.log("找到父级了===", parentsArr);
    formList.value = [
      {
        ...parentsArr[0],
        children: [_formData]
      }
    ];
    // console.log("添加，渲染二级===", formList.value, formData);
  } else if (level.value === 3) {
    let _formData3 = parentsArr[1];
    _formData3.children = [_formData];
    formList.value = [
      {
        ...parentsArr[0],
        children: [_formData3]
      }
    ];
    // console.log("添加，渲染三级===", formList.value, formData);
  }
};

const closeDialog = async () => {
  //   resetForm(); //清空表单
  const refs = formRef.value;
  for (let item of refs) {
    await item.resetFields();
  }
  formList.value = [
    {
      children: [
        // {
        //   level3: [{}]
        // }
      ]
    }
  ];
  emit("close");
};
const submit = async () => {
  console.log("formList表单数据===", formList.value);
  const DATA = JSON.parse(JSON.stringify(formList.value));
  const data1 = renameChildKey(DATA, "level2", "children");

  await validateFun(); //多表单校验
  if (isValidate.value) {
    // 多表单校验通过
    data1.map(item => {
      if (item.levelType === 3) {
        item.propTemplate = replaceNS(item.propTemplate, 1);
      }
    });
    emit("submit", data1, props.optionInfo.type, level.value);
  }
  // emit("submit", data1, props.optionInfo.type, level.value);
};

//多表单校验
const isValidate = ref(true); //表单是否校验通过
const validateFun = async () => {
  isValidate.value = true;
  const refs = formRef.value;
  for (let item of refs) {
    await item.validate((valid, fields) => {
      if (valid) {
        isValidate.value = true;
        console.log("submit!");
      } else {
        isValidate.value = false;
        console.log("error submit!", fields);
      }
    });
  }
};

const addLevel1 = () => {
  formList.value.push({
    children: [],
    required: 1,
    status: 1,
    speType: 1,
    sortOrder: 1,
    delFlag: 0
  });
};
const addLevel2 = (item, index) => {
  item.children.push({ delFlag: 0, sortOrder: 1 });
  console.log("图片继续添加", item);
};

const delLevel1 = (item, index) => {
  // if (formList.value.length <= 1) return ElMessage.error("至少保留一条数据");
  if (props.optionInfo.type === "edit") {
    console.log("编辑的时候，删除操作特殊处理");
    item.delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
  } else {
    formList.value.splice(index, 1);
  }
};
const delLevel2 = (item, index) => {
  // if (item.children.length <= 1) return ElMessage.error("至少保留一条数据");
  if (props.optionInfo.type === "edit") {
    console.log("编辑的时候，删除操作特殊处理");
    item.children[index].delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
  } else {
    item.children.splice(index, 1);
  }
};
const renameChildKey = (tree, orign_childKey, new_childKey) => {
  tree.forEach(item => {
    if (item[orign_childKey]) {
      item[new_childKey] = item[orign_childKey];
      delete item[orign_childKey];
    }
    if (item[new_childKey] && item[new_childKey].length > 0) {
      renameChildKey(item[new_childKey], orign_childKey, new_childKey);
    }
  });
  return tree;
};

// // 根据子id找父,返回值不包含查找的节点
// const findParentsId = (treeData, id) => {
//   if (treeData.length == 0) return;
//   for (let i = 0; i < treeData.length; i++) {
//     if (treeData[i].stastsId == id) {
//       return [];
//     } else {
//       if (treeData[i].children) {
//         let res = findParentsId(treeData[i].children, id);
//         if (res !== undefined) {
//           return res.concat({ ...treeData[i] }).reverse();
//         }
//       }
//     }
//   }
// };
// // 组织结构子id，找父
// const orgChildIdFindParent = (childId, orgList = []) => {
//   const result = findParentsId(orgList, childId);
//   return result || [];
// };

//====================================文件上传========================================================================================

const handleAvatarChangeIcon = (item, file, fileList) => {
  //选中文件触发的change事件
  // console.log(file);
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
  if (!isPNG && !isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  } else {
    item["statsText"] = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
    // console.log("这里调用图片上传接口");
    customUpload(item, { file }); //调用上传文件api接口
  }
};

/**
 * 上传
 */
const customUpload = async (item, option) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  // const objName = folder + option.file.name;
  const objName = folder + option.file.name.split(".")[0] + new Date().getTime() + "." + option.file.name.split(".")[1];

  ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl);
      item["statsText"] = res.fileUrl.split("?")[0];
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

//====================================富文本编辑器========================================================================================
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        const fileBase64 = fileToBase64Async(file);
        insertFn(fileBase64); // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
        console.log(fileBase64);
      }
    }
  }
};
const currentObj = ref({}); //当前点击的对象，用于富文本编辑器值的赋值

const fileToBase64Async = file => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = e => {
      resolve(e.target.result);
    };
  });
};

//打开属性说明 富文本编辑器
const clickAddAttrTips = async item => {
  currentObj.value = item;
  //   console.log("属性说明富文本框，节点信息===", item);
  const params = {
    sourceType: 1,
    sourceId: item.stastsId
  };
  valueHtml.value = "";
  await getRichText(params).then(res => {
    if (res.code === 200) {
      valueHtml.value = res.data.content;
      //   valueHtml.value = "123123";
    }
  });
  console.log("富文本编辑器内容===", valueHtml.value);

  dialogEditorVisible.value = true;
};
const closeEditorDialog = () => {
  dialogEditorVisible.value = false;
  valueHtml.value = "";
};
//保存富文本编辑器内容
const submitEditor = () => {
  const params = {
    sourceType: 1,
    sourceId: currentObj.value.stastsId,
    content: valueHtml.value
  };
  console.log("这是保存富文本的信息===", params);
  saveSassRichText(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "属性说明编辑成功",
        type: "success"
      });
      dialogEditorVisible.value = false;
      valueHtml.value = "";
    }
  });
};

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}
i {
  vertical-align: middle;
}
.hr {
  border-top: 1px solid #dcdfe6;
  margin: 20px 0;
}
.built_in_box {
  margin: 4px 0 0 100px;
}
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}
.avatar {
  width: 75px;
  height: 75px;
  border-radius: 6px;
}
.add-item2 {
  vertical-align: top;
  margin-top: 8px;
}
.level2-item {
  &:not(:last-of-type) {
    margin-bottom: 10px;
  }
  &:last-of-type {
    display: inline-block;
  }
}
.el-form--inline .el-form-item {
  margin-right: 10px;
}
.el-form-item {
  margin-bottom: 0;
}
.del-icon {
  cursor: pointer;
}
.add-attr {
  margin: 0 20px;
  font-size: 12px;
}
.add-item {
  font-size: 12px;
  &.add-item1 {
    margin-top: 10px;
  }
}
.del-wrap,
.add-wrap {
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.form-list {
  .el-form {
    &:not(:last-of-type) {
      margin-bottom: 20px;
    }
  }
}
.level1,
.level2 {
  background-color: #f5f7fa;
  padding: 20px 16px 0 16px;
}
.level2 {
  padding-top: 16px;
  padding-bottom: 20px;
  & > div.el-row {
    background-color: white;
    padding: 20px;
  }
}
.level3 {
  display: flex;
  flex-direction: column;
  .el-form-item {
    &:not(:last-of-type) {
      margin-bottom: 10px;
    }
  }
}
</style>
